package cn.itsource.hrm.service.impl;

import cn.itsource.hrm.constant.RedisConstant;
import cn.itsource.hrm.domain.VipBase;
import cn.itsource.hrm.domain.VipUser;
import cn.itsource.hrm.dto.UserRegisterDto;
import cn.itsource.hrm.exception.GlobalException;
import cn.itsource.hrm.mapper.VipBaseMapper;
import cn.itsource.hrm.mapper.VipUserMapper;
import cn.itsource.hrm.service.IVipUserService;
import cn.itsource.hrm.util.AssertUtils;
import cn.itsource.hrm.util.encrypt.MD5;
import cn.itsource.hrm.vo.SMSSendCodeVO;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author ¿­
 * @since 2021-01-24
 */
@Service
public class VipUserServiceImpl extends ServiceImpl<VipUserMapper, VipUser> implements IVipUserService {


    @Autowired
    private StringRedisTemplate template;

    @Autowired
    private VipBaseMapper vipBaseMapper;

    @Override
    public void register(UserRegisterDto dto) {
        // 1. 参数校验 -- 非空 合法
        String mobile = dto.getMobile();
        String password = dto.getPassword();
        Integer regChannel = dto.getRegChannel();
        String smsCode = dto.getSmsCode();

        // 1.2. 判断一下手机号是否已注册
        boolean flag = baseMapper.hasPhone(mobile);
        if(flag){
            throw new GlobalException("手机号是否已注册");
        }

        // 2. 短信验证码的校验
        // 2.1 根据手机号生成key
        String key = String.format(RedisConstant.SEND_SMS_KEY,mobile);
        // 2.2 根据key到redis取之前的验证码
        SMSSendCodeVO codeVO = JSON.parseObject(template.opsForValue().get(key), SMSSendCodeVO.class);
        // 2.3 对比
        AssertUtils.isnotNull("之前的验证码已过期，请重新获取",codeVO);
        AssertUtils.isNotEquals("短信验证码不正确",codeVO.getSmsCode(),smsCode);

        // 3. 封装对象到数据库
        // 3.1 封装对象 VipUser 用户登录信息
        VipUser vipUser = new VipUser();
        vipUser.setPhone(mobile);
        Date now = new Date();
        vipUser.setCreateTime(now.getTime());
        vipUser.setCreateTime(now.getTime());
        // 密码加盐
        String salt = MD5.getRandomCode(18);
        password = MD5.getMD5(password + salt);

        vipUser.setSalt(salt);
        vipUser.setPassword(password);
        vipUser.setNickName(mobile);

        // 短信注册，绑定手机号，添加位状态
        vipUser.addState(VipUser.PHONE_BAND_STATE);

        // 4. 先保存User
        baseMapper.insert(vipUser);

        // 3.2 封装 BaseUser 用户的基本信息
        VipBase vipBase = new VipBase();
        vipBase.setCreateTime(now.getTime());
        vipBase.setSsoId(vipUser.getId());
        vipBase.setRegChannel(regChannel);
        vipBase.setRegTime(now.getTime());

        // 4.2 在保存 Base；
        vipBaseMapper.insert(vipBase);

    }
}
